#!/bin/bash

# 部署配置
DEPLOY_USER="pyapp"
DEPLOY_HOST="222.128.36.213"
DEPLOY_PORT="6022"
NGINX_PATH="/home/pyapp/nginx"
WWW_PATH="/home/pyapp/www/cardsys_test"

# SSH 命令基础，包含端口
SSH_CMD="ssh -p ${DEPLOY_PORT} -o StrictHostKeyChecking=no"
SCP_CMD="scp -P ${DEPLOY_PORT} -o StrictHostKeyChecking=no"

echo "准备上传 Nginx 配置..."

# 创建 Nginx 配置
cat > nginx_cardsys_test.conf << EOL
# 卡系统测试平台 Nginx 配置
# 此配置应该被包含在 nginx.conf 的 http 块中

server {
    listen 8800;
    server_name localhost;

    access_log ${NGINX_PATH}/logs/cardsys_test_access.log;
    error_log ${NGINX_PATH}/logs/cardsys_test_error.log;

    # 前端静态文件服务
    location / {
        root ${WWW_PATH};
        index index.html;
        try_files \$uri \$uri/ /index.html;

        # 缓存配置
        expires 1h;
        add_header Cache-Control "public, no-transform";
    }

    # 后端 API 代理
    location /api/ {
        proxy_pass http://127.0.0.1:8116/;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;

        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOL

# 上传 Nginx 配置
echo "上传 Nginx 配置..."
${SCP_CMD} nginx_cardsys_test.conf ${DEPLOY_USER}@${DEPLOY_HOST}:${NGINX_PATH}/conf/

# 创建一个临时的包含文件，用于在 http 块中引入我们的配置
cat > include_command.sh << EOL
#!/bin/bash

# 检查 nginx.conf 文件
NGINX_CONF="${NGINX_PATH}/conf/nginx.conf"

# 备份原始配置
cp \${NGINX_CONF} \${NGINX_CONF}.bak

# 检查是否已经包含了我们的配置
if grep -q "include.*nginx_cardsys_test.conf" \${NGINX_CONF}; then
    # 已经包含，不需要修改
    echo "配置已存在，无需修改"
else
    # 查找 http 块的结束位置
    HTTP_END=\$(grep -n "}" \${NGINX_CONF} | grep -B1 "http" | head -1 | cut -d: -f1)
    
    if [ ! -z "\${HTTP_END}" ]; then
        # 在 http 块结束前插入我们的 include 语句
        sed -i "\${HTTP_END}i\\    include ${NGINX_PATH}/conf/nginx_cardsys_test.conf;" \${NGINX_CONF}
        echo "配置已添加到 nginx.conf 的 http 块中"
    else
        echo "无法找到 http 块，请手动修改 nginx.conf"
    fi
fi

# 测试配置
${NGINX_PATH}/sbin/nginx -t

# 如果配置正确，重新加载 Nginx
if [ \$? -eq 0 ]; then
    ${NGINX_PATH}/sbin/nginx -s reload
    echo "Nginx 配置已重新加载"
else
    echo "Nginx 配置有误，请检查"
fi
EOL

# 上传并执行包含命令脚本
echo "更新 Nginx 主配置并重启..."
${SCP_CMD} include_command.sh ${DEPLOY_USER}@${DEPLOY_HOST}:/tmp/
${SSH_CMD} ${DEPLOY_USER}@${DEPLOY_HOST} "chmod +x /tmp/include_command.sh && /tmp/include_command.sh"

# 清理临时文件
rm include_command.sh

echo "Nginx 配置更新完成！" 